<?php

namespace Database\Seeders;

use App\Models\Vocabulary\Vocabulary;
use App\Models\Vocabulary\VocabularyOption;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class VocabularyDataSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $vocabularys = DB::connection('rjmysql')->table('vocabularys')->get()->toArray();
        $vocabularys = json_decode(json_encode($vocabularys), true);

        foreach ($vocabularys as $vocabulary) {
            if (DB::table('categorys')->where('id', $vocabulary['category_id'])->exists() &&
                DB::table('click_learns')->where('id', $vocabulary['click_learn_id'])->exists()) {
                Vocabulary::query()->updateOrCreate(
                    ['id' => $vocabulary['id']],
                    $vocabulary
                );
                $this->save_vocabulary_options($vocabulary['id']);
            }
        }

        $this->command->info('单元词汇表数据填充完成！');
    }

    protected function save_vocabulary_options(int $vocabulary_id): void
    {
        $vocabulary_options = DB::connection('rjmysql')->table('vocabulary_options')
            ->where('vocabulary_id', $vocabulary_id)->get()->toArray();
        $vocabulary_options = json_decode(json_encode($vocabulary_options), true);

        foreach ($vocabulary_options as $vocabulary_option) {
            VocabularyOption::query()->updateOrCreate(
                ['id' => $vocabulary_option['id']],
                $vocabulary_option
            );
        }
    }
}
